<template>
  <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option v-for="item in list" :key="item.id" :value="item.username" :label="item.username" />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { addDepartments, editDepartments, getDepartmentsDetail, getEmployeesSimple } from '@/api/department'
export default {
  props: {
    originList: {
      type: Array,
      required: true
    },
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    // 自定义检验规则函数
    const existCodeValid = (rule, value, callback) => {
      //  验证编码value在所有的部门是否存在
      let existCodeList = this.originList.map(item => item.code)
      // 确认是否是编辑状态
      if (this.isEdit) {
        // 根据id 将当前编辑的部门id 从所以的部门中移除
        existCodeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      console.log(existCodeList, 'existCodeList')
      if (existCodeList.includes(value)) {
        // 存在,效验失败
        callback(new Error(`部门编码${value}已存在`))
      } else {
        // 不存在, 放行 callback()
        callback()
      }
    }
    // 自定义名称效验规则
    const existNameValid = (rule, value, callback) => {
      //  验证输入部门名称value在同级不能重复
      const existNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      console.log(existNameList, 'existNameList')
      // 是否是编辑状态
      // 确认是否是编辑状态
      if (this.isEdit) {
        // 根据id 将当前编辑的部门id 从所以的部门中移除
        const pid = this.originList.find(item => item.id === this.id).pid // 获取pid
        const brothers = this.originList.filter(item => item.pid === pid) // 把所有pid相同的兄弟包装一起
        brothers.filter(item => item.id !== this.id).map(item => item.name) // 排除自己
      }
      // 如果包含这个名称
      if (existNameList.includes(value)) {
        // 存在,效验失败
        callback(new Error(`部门名称${value}已存在`))
      } else {
        // 不存在, 放行 callback()
        callback()
      }
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      list: [], // 部门负责人
      // 检验规则对象 指定 el-form必填 指定prop检验
      rules: {
        name: [
          { required: true, message: '请输入部门的名称', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入长度是1~50的部门名称', trigger: 'blur' },
          { validator: existNameValid, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门的编码', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入长度是1~50的部门编码', trigger: 'blur' },
          { validator: existCodeValid, trigger: 'blur' }],
        manager: [
          { required: true, message: '请选择部门负责人', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '请输入部门的介绍', trigger: 'blur' },
          { min: 1, max: 300, message: '请输入长度是1~300的部门名称', trigger: 'blur' }
        ]
      }
    }
  },
  // id 一旦改变就重新获取数据,深度侦听
  // watch: {
  //   id: {
  //     handler: function(new_val, old_val) {
  //       console.log(new_val, 'new_val')
  //       console.log(old_val, 'old_val')
  //       this.loadDepartmentsDetail()
  //     },
  //     immediate: true,
  //     deep:true
  //   }
  // },
  watch: {
    id: function(newVal, oldVal) {
      this.loadDepartmentsDetail()
    }
  },
  created() {
    this.loadEmployeesSimple()
    if (this.isEdit) {
      this.loadDepartmentsDetail()
    }
  },
  methods: {
    async loadEmployeesSimple() {
      try {
        const res = await getEmployeesSimple()
        console.log(res, '负责人数据')
        this.list = res.data
      } catch (error) {
        console.log(error
        )
      }
    },
    async doAdd() {
      try {
        const res = await addDepartments({ ...this.form, pid: this.id })
        console.log(res, 'deDepartment')
        // 子传父关闭页面
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    async loadDepartmentsDetail() {
      try {
        const res = await getDepartmentsDetail(this.id)
        console.log(res, 'DepartmentsDetail')
        // 将数据填充到表单
        this.form = res.data
      } catch (error) {
        console.log(error
        )
      }
    },
    async doEdit() {
      // 实现编辑部门功能
      try {
        const res = await editDepartments(this.form)
        console.log(res, 'EDitDepartments')
        // 子传父 关闭弹层,重新渲染页面
        this.$emit('success')
      } catch (error) {
        console.log(error
        )
      }
    },
    hSubmit() {
    //
      this.$refs.deptForm.validate((valid) => {
      // 检验失败
        if (!valid) return
        // 检验通过
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    hCancel() {
      this.$emit('close')
    },
    resetForm() {
      this.$refs.deptForm.resetFields() // 清空表单
    }
  }
}
</script>
